/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/5/22.
//

#include "sql/stmt/update_stmt.h"
#include "common/log/log.h"
#include "storage/db/db.h"
#include "storage/table/table.h"
#include "sql/stmt/select_stmt.h"

UpdateStmt::UpdateStmt(Table *table, const vector<Expression*>& expressions, vector<string> attrs, FilterStmt *filter_stmt)
    : table_(table), expressions_(expressions), attrs_(std::move(attrs)), filter_stmt_(filter_stmt)
{}



RC UpdateStmt::create(Db *db, const UpdateSqlNode &update, Stmt *&stmt)
{
  // TODO
  const char *table_name = update.relation_name.c_str();
  if (nullptr == db || nullptr == table_name || update.expressions.empty()) {
    LOG_WARN("invalid argument. db=%p, table_name=%p, value_num=%d",
        db, table_name, static_cast<int>(update.expressions.size()));
    return RC::INVALID_ARGUMENT;
  }

  // check whether the table exists
  Table *table = db->find_table(table_name);
  if (nullptr == table) {
    LOG_WARN("no such table. db=%s, table_name=%s", db->name(), table_name);
    return RC::SCHEMA_TABLE_NOT_EXIST;
  }
  
  if (update.attribute_names.size() != update.expressions.size()) {
    LOG_WARN("schema mismatch. value num=%d, field num in schema=%d",
        static_cast<int>(update.expressions.size()), static_cast<int>(table->table_meta().field_num()));
    return RC::SCHEMA_FIELD_MISSING;
  }

  // check the fields number
  //const Expression* *expressions = update.expressions.data();
  //const int    expression_num = static_cast<int>(update.expressions.size());

  for(auto expr: update.expressions)
  {
    if (expr == nullptr) {
      LOG_WARN("invalid argument. value is null");
      return RC::INVALID_ARGUMENT;
    }
    if(expr->type()==ExprType::SUBQUERY)
    {
      Stmt* stmt = nullptr;
      RC rc = SelectStmt::create(db, static_cast<SubqueryExpr*>(expr)->select_sql_node()->selection, stmt);
      if(rc != RC::SUCCESS) {
        LOG_WARN("failed to create select statement for subquery");
        return rc;
      }
      static_cast<SubqueryExpr*>(expr)->set_stmt(static_cast<SelectStmt*>(stmt));
    }
  }
  

  int cnt = 0;
  for (const string &attr_name : update.attribute_names) {
    const FieldMeta *fieldmeta = table->table_meta().field(attr_name.c_str());
    if (fieldmeta == nullptr) {
      LOG_WARN("no such field in table. table=%s, field=%s", table->name(), attr_name.c_str());
      return RC::SCHEMA_FIELD_MISSING;
    }
    if (fieldmeta->nullable() == false && update.expressions[cnt]->value_type() == AttrType::NULLS) {
      LOG_WARN("can not set null to non-nullable field. table=%s, field=%s", table->name(), attr_name.c_str());
      return RC::INVALID_ARGUMENT;
    }
    cnt++;
    //check type in the execution stage

    // else if (fieldmeta->type() != values[cnt++].attr_type()) {
    //   LOG_WARN("schema mismatch. field=%s\n",attr_name.c_str());
    //   return RC::INVALID_ARGUMENT;
    // }

  }


  FilterStmt *filter_stmt = nullptr;
  unordered_map<string, Table *> table_map;
  table_map.insert(pair<string, Table *>(string(table_name), table));
  RC rc = FilterStmt::create(
      db, table, &table_map, update.conditions.conditions.data(), static_cast<int>(update.conditions.conditions.size()), filter_stmt,BinderContext(),update.conditions.logic_op);
  if (rc != RC::SUCCESS) {
    return rc;
  }
  
  // everything alright
  stmt = new UpdateStmt(table, update.expressions, update.attribute_names, filter_stmt);

  return RC::SUCCESS;
}
